<?php 
namespace App\Http\Controllers\Api\v1\Check;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Input;
use App\Models\Api\Appid;
use Db,Request;
/**
* 接口调用验证
*/
class AppController extends Controller
{
    /**
     * 获取AccessToken
     * 8888888888
     * BxjXK]Nxlu@)CBYt2%0_NTDNvJPga0gp
     * 6666666666
     * %]yB8yBmfehay@QyV$!l@]8aK3PXa:6g
     * @return [type] [description]
     */
	public function getaccesstoken()
	{    
		$appid = Input::get('appid');// 应用id
		$appsecret = htmlspecialchars(Input::get('appsecret'));// 应用密钥
		if(!$appid || strlen($appid) != 10)
		{
			return response()->json(['code'=>10101,'msg'=>'invalid appid']);
		}
		if(!$appsecret || strlen($appsecret) != 32)
		{
			return response()->json(['code'=>10102,'msg'=>'invalid secret']);
		}

		$time = time();
		// 强制刷新access_token
		if($refresh_token = Input::get('refresh_token'))
		{
			$data = Appid::where("app_refreshtoken",$refresh_token) -> first();
			if(empty($data))
			{
				return response()->json(['code'=>10103,'msg'=>'Invalid Refresh_token']);
			}
			$accesstoken = 'GD'.$time.md5($appid.$appsecret).round_str(32);// 生成新的accesstoken
			$refreshtoken = 'GD'.$time.md5($appid.$appsecret).round_str(84);// 生成新的refreshtoken
			// 更新返回受影响条数
			if(Appid::where('id',$data['id']) -> update(['app_accesstoken'=>$accesstoken,'app_refreshtoken'=>$refreshtoken,'app_gettime'=>$time]))
			{
				return response()->json(['code'=>200,'data'=>[
					'access_token'=>$accesstoken,
					'refresh_token'=>$refreshtoken,
					'expire_time'=>$time+$data['app_expire']
				],'msg'=>'ok']);
			}
			// 更新失败
			else
			{
				return response()->json(['code'=>10104,'msg'=>'failed']);
			}
		}

		$data = Appid::where(["appid"=>$appid, "appsecret"=>$appsecret])->first();
		// 应用id或密钥错误
		if(empty($data))
		{
			return response()->json(['code'=>10105,'msg'=>'invalid Appid Or Secret']);
		}
		// 生成接口唯一密钥
		else
		{
			// accesstoken 尚未过期
			if(isset($data['app_gettime']) && $data['app_gettime'] + $data['app_expire'] > $time)
			{
				// echo 123;exit;
				return response()->json(['code'=>200,'data'=>[
					'access_token'=>$data['app_accesstoken'],
					'refresh_token'=>$data['app_refreshtoken'],
					'expire_time'=>$data['app_gettime'] + $data['app_expire']
				],'msg'=>'ok']);
			}
			// 已过期 需要重新生成
			else
			{
				$accesstoken = 'GD'.$time.md5($appid.$appsecret).round_str(32);// 生成新的accesstoken
//				$refreshtoken = 'GD'.$time.md5($appid.$appsecret).round_str(84);// 生成新的refreshtoken
                $refreshtoken = $data['app_refreshtoken'];
				// 更新返回受影响条数
				if(Appid::where('id',$data['id'])-> update(['app_accesstoken'=>$accesstoken,'app_refreshtoken'=>$refreshtoken,'app_gettime'=>$time]))
				{
					return response()->json(['code'=>200,'data'=>[
						'access_token'=>$accesstoken,
						'refresh_token'=>$refreshtoken,
						'expire_time'=>$time+$data['app_expire']
					],'msg'=>'ok']);
				}
				// 更新失败
				else
				{
					return response()->json(['code'=>10106,'msg'=>'failed']);
				}
			}
		}
	}

    /**
     * 获取AccessToken
     * 8888888888
     * BxjXK]Nxlu@)CBYt2%0_NTDNvJPga0gp
     * 6666666666
     * %]yB8yBmfehay@QyV$!l@]8aK3PXa:6g
     * @return [type] [description]
     */
	public function getaccesstoken_safe()
    {
//        $this->redis = new Redis();

        $appid_secret = Input::get("appid_secret");

      
        $appidsec = json_decode(privDecrypt($appid_secret),true);
        
        if(!$appidsec || empty($appidsec))
        {
            return json_encode(['code'=>10101,'msg'=>'invalid.']);
        }
        $appid = $appidsec['appid'];// 应用id
        $appsecret = $appidsec['appsecret'];// 应用密钥

        if(!$appid || strlen($appid) != 10)
        {
            return json_encode(['code'=>10101,'msg'=>'invalid appid']);
        }
        if(!$appsecret || strlen($appsecret) != 32)
        {
            return json_encode(['code'=>10102,'msg'=>'invalid secret']);
        }

        $time = time();
        // 强制刷新access_token
        if($refresh_token = Input::get('refresh_token'))
        {
            $data = Appid::where("app_refreshtoken",$refresh_token) -> first();
            if(empty($data))
            {
                return json_encode(['code'=>10103,'msg'=>'Invalid Refresh_token']);
            }
            $accesstoken = 'GD'.$time.md5($appid.$appsecret).round_str(32);// 生成新的accesstoken
            $refreshtoken = 'GD'.$time.md5($appid.$appsecret).round_str(84);// 生成新的refreshtoken
            // 更新返回受影响条数
            if(Appid::where('id',$data['id']) -> update(['app_accesstoken'=>$accesstoken,'app_refreshtoken'=>$refreshtoken,'app_gettime'=>$time]))
            {
                // 记录接口日志

                return json_encode(['code'=>200,'data'=>[
                    'access_token'=>$accesstoken,
                    'refresh_token'=>$refreshtoken,
                    'expire_time'=>$time+$data['app_expire']
                ],'msg'=>'ok']);
            }
            // 更新失败
            else
            {
                return json_encode(['code'=>10104,'msg'=>'failed']);
            }
        }


//        $data = $this->redis->get("app_accesstoken");
//        if(!$data)
//        {
            // redis缓存中  不存在  则去数据库中查询
            $data = Appid::where(["appid"=>$appid,"appsecret"=>$appsecret]) -> first();
            // 应用id或密钥错误
            if(empty($data))
            {
                return json_encode(['code'=>10105,'msg'=>'invalid Appid Or Secret']);
            }
            // 生成接口唯一密钥
            else
            {
//             accesstoken 尚未过期
                if(isset($data['app_gettime']) && $data['app_gettime'] + $data['app_expire'] > $time)
                {
                    return json_encode(['code'=>200,'data'=>[
                        'access_token'=>privEncrypt($data['app_accesstoken']),
                        'refresh_token'=>$data['app_refreshtoken'],
                        'expire_time'=>$data['app_gettime'] + $data['app_expire']
                    ],'msg'=>'ok']);
                }
                // 已过期 需要重新生成
                else
                {
                    $accesstoken = 'GD'.$time.md5($appid.$appsecret).round_str(32);// 生成新的accesstoken
//				$refreshtoken = 'GD'.$time.md5($appid.$appsecret).round_str(84);// 生成新的refreshtoken
                    $refreshtoken = $data['app_refreshtoken'];
                    // 更新返回受影响条数
                    if(Appid::where('id',$data['id']) ->update(['app_accesstoken'=>$accesstoken,'app_refreshtoken'=>$refreshtoken,'app_gettime'=>$time]))
                    {
                        return json_encode(['code'=>200,'data'=>[
                            'access_token'=>privEncrypt($accesstoken),
                            'refresh_token'=>$refreshtoken,
                            'expire_time'=>$time+$data['app_expire']
                        ],'msg'=>'ok']);
                    }
                    // 更新失败
                    else
                    {
                        return json_encode(['code'=>10106,'msg'=>'failed']);
                    }
                }
            }
//        }
//        $data = DB::table('appid') -> where("`appid`=$appid AND `appsecret`='$appsecret'") -> find();
//        // 应用id或密钥错误
//        if(empty($data))
//        {
//            return json_encode(['code'=>10105,'msg'=>'invalid Appid Or Secret']);
//        }
//        // 生成接口唯一密钥
//        else
//        {
////             accesstoken 尚未过期
//            if(isset($data['app_gettime']) && $data['app_gettime'] + $data['app_expire'] > $time)
//            {
//                return json_encode(['code'=>200,'data'=>[
//                    'access_token'=>privEncrypt($data['app_accesstoken']),
//                    'refresh_token'=>$data['app_refreshtoken'],
//                    'expire_time'=>$data['app_gettime'] + $data['app_expire']
//                ],'msg'=>'ok']);
//            }
//            // 已过期 需要重新生成
//            else
//            {
//                $accesstoken = 'GD'.$time.md5($appid.$appsecret).round_str(32);// 生成新的accesstoken
////				$refreshtoken = 'GD'.$time.md5($appid.$appsecret).round_str(84);// 生成新的refreshtoken
//                $refreshtoken = $data['app_refreshtoken'];
//                // 更新返回受影响条数
//                if(DB::table('appid') -> update(['id'=>$data['id'],'app_accesstoken'=>$accesstoken,'app_refreshtoken'=>$refreshtoken,'app_gettime'=>$time]))
//                {
//                    return json_encode(['code'=>200,'data'=>[
//                        'access_token'=>privEncrypt($accesstoken),
//                        'refresh_token'=>$refreshtoken,
//                        'expire_time'=>$time+$data['app_expire']
//                    ],'msg'=>'ok']);
//                }
//                // 更新失败
//                else
//                {
//                    return json_encode(['code'=>10106,'msg'=>'failed']);
//                }
//            }
//        }
    }
}